<?php

class Db_Tables2_TDealer
{
	function __construct() {
		$this->dealers_db = Zend_Registry::get("dealers_db");
	}
	
	function GetDealerArr($keyword)
	{
		$result = array();
		
		$keyword = trim($keyword);
	
		if(1 < mb_strlen($keyword))
		{
			$select = $this->dealers_db->select();
			$select->from("t_dealer", array("id", "name", "companyName"));
			$select->where("name like \"%".$keyword."%\" or companyName like \"%".$keyword."%\" or address like \"%".$keyword."%\" or tel like \"%".$keyword."%\"");
			$select->where("state = ?", 1);
			$select->where("authState = ?", 1);
			$data = $this->dealers_db->fetchAll($select);
			
			if(!empty($data))
			{
				foreach($data as $d)
				{
					$result[] = array(
						"id" => $d['id'],
						"name" => $d['name']." [".$d['companyName']."]"
					);
				}
			}
		}
		
		return $result;
	}
	
	function FetchDealerDetail($dealer_id)
	{
		$result = array();
		
		if($dealer_id)
		{
			$select = $this->dealers_db->select();
			$select->from("t_dealer", "*");
			$select->where("id = ?", $dealer_id);
			$row = $this->dealers_db->fetchRow($select);
			
			if($row)
			{
				$result = $row;
			}
		}
		
		return $result;
	}
	
	function SearchDealerByKeyword($keyword, $type) //type 1=company name
	{
		$result = 0; //dealer id
		
		if($keyword && $type)
		{
			if(1 == $type) //by company name
			{
				$select = $this->dealers_db->select();
				$select->from("t_dealer", array("id"));
				$select->where("companyName = ?", trim($keyword));
				$row = $this->dealers_db->fetchRow($select);
				
				if($row)
				{
					$result = $row['id'];
				}
			}
		}
		
		return $result;
	}
	
	function GetDealerInSameName($keyword, $type=1)
	{
		$result = array();
		
		$select = $this->dealers_db->select();
		$select->from("t_dealer as d", array("id", "address", "companyName"));
		$select->where("d.companyName = ?", trim($keyword));
		$rows = $this->dealers_db->fetchAll($select);

		if($rows)
		{
			foreach($rows as $row)
			{
				$select = $this->dealers_db->select();
				$select->from("t_dealer_brand as db", array());
				$select->joinLeft("cars_db.t_brand as b", "b.id=db.brandId", array("name as brand_name"));
				$select->where("db.dealerId = ?", $row['id']);
				$brows = $this->dealers_db->fetchAll($select);
				
				$brands = array();
				
				if(!empty($brows))
				{
					foreach($brows as $brow)
					{
						$brands[] = $brow['brand_name'];
					}
				}
				
				$f = array(
					"dealer_id" => $row['id'],
					"company_name" => $row['companyName'],
					"address" => $row['address'],
					"brands" => $brands
				);
				
				$result[] = $f;
			}
		}
		
		return $result;
	}
}